<template>
  <view class="cinema-detail-page">
    <!-- Header Bar -->
    <view class="header-bar">
      <view class="back-icon" @tap="goBack">
        <image src="/static/images/back-arrow-white.png" mode="aspectFit" />
      </view>
      <text class="title">影院</text>
    </view>

    <!-- Main Content Area -->
    <scroll-view scroll-y class="main-container">
      <!-- Cinema Info -->
      <view class="cinema-info-box">
        <view class="cinema-name">{{ cinemaInfo.name }}</view>
        <view class="cinema-address">{{ cinemaInfo.specifiedAddress }}</view>
        <view class="cinema-phone">{{ cinemaInfo.phone }}</view>
      </view>

      <!-- Movie Scroller -->
      <view class="movie-scroller-wrapper">
        <scroll-view class="movie-scroll-view" scroll-x :show-scrollbar="false" :scroll-into-view="'movie-item-' + selectedMovieIndex">
          <view
            v-for="(movie, index) in moviesInCinema"
            :key="movie.movie_id"
            :id="'movie-item-' + index"
            class="movie-poster-item"
            :class="{ active: selectedMovieIndex === index }"
            @tap="selectMovie(index)"
          >
            <image :src="getPoster(movie.poster)" mode="aspectFill" />
          </view>
        </scroll-view>
      </view>

      <!-- Selected Movie Info -->
      <view class="selected-movie-info" v-if="selectedMovie">
        <view class="movie-title">
          <text class="name">{{ selectedMovie.movie_name }}</text>
          <text class="score">{{ selectedMovie.score ? selectedMovie.score.toFixed(1) + '分' : '暂无评分' }}</text>
        </view>
        <view class="movie-meta">
          <text>{{ selectedMovie.movie_long }}分钟</text>
          <text class="divider">|</text>
          <text>{{ selectedMovie.type }}</text>
          <text class="divider">|</text>
          <text class="actors">{{ selectedMovie.actor }}</text>
        </view>
      </view>
      
      <!-- Divider -->
      <view class="divider-line"></view>

      <!-- Date and Schedule Section -->
      <view class="schedule-section" v-if="selectedMovie">
        <!-- Date Selector -->
        <view class="date-selector-container">
          <scroll-view class="date-scroll-view" scroll-x :show-scrollbar="false">
            <view
              v-for="(item, index) in availableDates"
              :key="index"
              class="date-item"
              :class="{ active: selectedDateIndex === index }"
              @tap="selectDate(index)"
            >
              <text>{{ formatDate(item.date) }}</text>
            </view>
          </scroll-view>
        </view>

        <!-- Schedule List -->
        <view class="schedule-list">
          <view v-if="schedulesForDate.length > 0">
            <view class="schedule-item" v-for="(schedule, index) in schedulesForDate" :key="index">
              <view class="time-info">
                <text class="start-time">{{ schedule.show_time }}</text>
                <text class="end-time">{{ calculateEndTime(schedule) }} 散场</text>
              </view>
              <view class="hall-info">
                <text class="language-hall">{{ schedule.language }}3D</text>
                 <text class="language-hall">{{ schedule.hall_name }}</text>
              </view>
              <view class="price-info">
                <text class="price">¥{{ schedule.price.toFixed(2) }}</text>
              </view>
              <view class="buy-button-wrapper">
                <button class="buy-btn" @tap="goToSelectSeat(schedule)">购票</button>
              </view>
            </view>
          </view>
          <view v-else class="no-schedule">
            <text>今日暂无排片</text>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      cinemaId: null,
      initialMovieId: null,
      cinemaInfo: {},
      moviesInCinema: [], // All movies available in this cinema
      selectedMovieIndex: 0,
      
      allSchedulesForMovie: [], // All schedules for the selected movie
      availableDates: [], // Unique dates for the selected movie
      selectedDateIndex: 0,

      schedulesForDate: [], // Schedules for the selected date
    };
  },
  computed: {
      selectedMovie() {
          if (this.moviesInCinema.length > this.selectedMovieIndex) {
              return this.moviesInCinema[this.selectedMovieIndex];
          }
          return null;
      }
  },
  onLoad(options) {
    if (options.cinema_id) {
      this.cinemaId = options.cinema_id;
      this.initialMovieId = options.movie_id; // Movie ID from previous page
      this.loadCinemaInfo();
      this.loadMoviesInCinema();
    }
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    getPoster(path) {
      if (!path) return '/static/images/placeholder.png';
      if (path.startsWith('http')) return path;
      return 'http://localhost:9090' + path;
    },
    // 1. Load basic cinema info
    loadCinemaInfo() {
      uni.request({
        url: `http://localhost:9090/selectCinemaInfo?id=${this.cinemaId}`,
        method: 'GET',
        success: (res) => {
          if (res.data.code === 1) {
            this.cinemaInfo = res.data.cinema;
          }
        },
      });
    },
    // 2. Load all movies that have schedules in this cinema
    loadMoviesInCinema() {
      uni.request({
        url: `http://localhost:9090/findCinemaSchedule?cinemaId=${this.cinemaId}`,
        method: 'GET',
        success: (res) => {
          if (res.data.code === 1 && res.data.schedule.length > 0) {
            this.moviesInCinema = res.data.schedule;
            // Find the index of the movie passed from the previous page
            const initialIndex = this.moviesInCinema.findIndex(m => m.movie_id == this.initialMovieId);
            this.selectedMovieIndex = initialIndex !== -1 ? initialIndex : 0;
            
            // 3. Load schedules for the initially selected movie
            this.loadSchedulesForMovie(this.moviesInCinema[this.selectedMovieIndex].movie_id);
          }
        },
      });
    },
    // 3. Load all schedules for a given movie ID in this cinema
    loadSchedulesForMovie(movieId) {
        uni.request({
            url: `http://localhost:9090/findCinemaMovieSchedule?cinemaId=${this.cinemaId}&movieId=${movieId}`,
            method: 'GET',
            success: (res) => {
                if(res.data.code === 1) {
                    this.allSchedulesForMovie = res.data.movieSchedules;
                    this.processSchedules();
                } else {
                    this.allSchedulesForMovie = [];
                    this.processSchedules();
                }
            }
        })
    },
    // 4. Process schedules to find unique dates and filter for the first date
    processSchedules() {
        const uniqueDates = [];
        const dateSet = new Set();
        this.allSchedulesForMovie.forEach(schedule => {
            if (!dateSet.has(schedule.show_date)) {
                dateSet.add(schedule.show_date);
                uniqueDates.push({ date: schedule.show_date });
            }
        });
        uniqueDates.sort((a,b) => new Date(a.date) - new Date(b.date));
        this.availableDates = uniqueDates;
        
        // Reset and show schedules for the first available date
        this.selectedDateIndex = 0;
        this.filterSchedulesByDate();
    },
    // 5. Filter schedules for the currently selected date
    filterSchedulesByDate() {
        if (this.availableDates.length > 0) {
            const selectedDate = this.availableDates[this.selectedDateIndex].date;
            this.schedulesForDate = this.allSchedulesForMovie.filter(s => s.show_date === selectedDate);
        } else {
            this.schedulesForDate = [];
        }
    },
    // Event Handlers
    selectMovie(index) {
      if (this.selectedMovieIndex === index) return;
      this.selectedMovieIndex = index;
      const movieId = this.moviesInCinema[index].movie_id;
      // Reset schedules and dates before loading new ones
      this.allSchedulesForMovie = [];
      this.availableDates = [];
      this.schedulesForDate = [];
      this.loadSchedulesForMovie(movieId);
    },
    selectDate(index) {
        this.selectedDateIndex = index;
        this.filterSchedulesByDate();
    },
    formatDate(dateStr) {
        if (!dateStr) return '';
        const date = new Date(dateStr);
        return `${date.getMonth() + 1}月${date.getDate()}日`;
    },
    calculateEndTime(schedule) {
        const startTime = schedule.show_time;
        const duration = parseInt(schedule.movie_long);
        if (!startTime || !duration) return '';

        const [startHours, startMinutes] = startTime.split(':').map(Number);
        const totalStartMinutes = startHours * 60 + startMinutes;
        const totalEndMinutes = totalStartMinutes + duration;

        const endHours = Math.floor(totalEndMinutes / 60) % 24;
        const endMinutes = totalEndMinutes % 60;

        return `${String(endHours).padStart(2, '0')}:${String(endMinutes).padStart(2, '0')}`;
    },
    goToSelectSeat(schedule) {
        uni.navigateTo({
            url: `/pages/select-seat/select-seat?schedule_id=${schedule.id}`
        });
    }
  },
};
</script>

<style>
page {
  background-color: #fff;
}
.cinema-detail-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
}
.header-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 88rpx;
  background-color: #dd2727;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  z-index: 100;
}
.back-icon {
  position: absolute;
  left: 20rpx;
  width: 40rpx;
  height: 40rpx;
}
.back-icon image {
  width: 100%;
  height: 100%;
}
.title {
  font-size: 32rpx;
  font-weight: bold;
}
.main-container {
  margin-top: 88rpx;
  height: calc(100vh - 88rpx);
}
.cinema-info-box {
  padding: 30rpx;
  border-bottom: 20rpx solid #f4f4f4;
}
.cinema-name {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}
.cinema-address, .cinema-phone {
  font-size: 26rpx;
  color: #666;
  margin-top: 15rpx;
}
.movie-scroller-wrapper {
  background-color: #474747;
  padding: 40rpx 0;
}
.movie-scroll-view {
  white-space: nowrap;
}
.movie-poster-item {
  display: inline-block;
  width: 200rpx;
  height: 280rpx;
  margin: 0 30rpx;
  transition: transform 0.3s;
  transform: scale(0.85);
  opacity: 0.7;
}
.movie-poster-item.active {
  transform: scale(1);
  opacity: 1;
}
.movie-poster-item image {
  width: 100%;
  height: 100%;
  border-radius: 8rpx;
}
.selected-movie-info {
  text-align: center;
  padding: 30rpx;
}
.movie-title {
  display: flex;
  justify-content: center;
  align-items: baseline;
  font-size: 34rpx;
}
.movie-title .name {
  font-weight: bold;
  color: #333;
}
.movie-title .score {
  font-size: 24rpx;
  color: #ffb400;
  margin-left: 15rpx;
  font-weight: bold;
}
.movie-meta {
  font-size: 24rpx;
  color: #666;
  margin-top: 15rpx;
}
.movie-meta .divider {
  margin: 0 10rpx;
}
.movie-meta .actors {
  display: inline-block;
  max-width: 400rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  vertical-align: middle;
}
.divider-line {
  height: 20rpx;
  background-color: #f4f4f4;
}
.date-selector-container {
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}
.date-scroll-view {
  white-space: nowrap;
  padding: 0 20rpx;
}
.date-item {
  display: inline-block;
  padding: 10rpx 25rpx;
  margin-right: 20rpx;
  font-size: 28rpx;
  color: #333;
}
.date-item.active {
  color: #dd2727;
  border-bottom: 2rpx solid #dd2727;
}
.schedule-list {
  padding: 0 30rpx;
}
.schedule-item {
  display: flex;
  align-items: center;
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}
.time-info, .hall-info {
  display: flex;
  flex-direction: column;
}
.time-info {
  width: 25%;
}
.start-time {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}
.end-time {
  font-size: 22rpx;
  color: #999;
  margin-top: 5rpx;
}
.hall-info {
    width: 30%;
}
.language-hall {
  font-size: 26rpx;
  color: #333;
}
.price-info {
  width: 25%;
  font-size: 32rpx;
  font-weight: bold;
  color: #dd2727;
}
.buy-button-wrapper {
  width: 20%;
  display: flex;
  justify-content: flex-end;
}
.buy-btn {
  padding: 10rpx 25rpx;
  font-size: 26rpx;
  background-color: #fff;
  color: #dd2727;
  border: 1rpx solid #dd2727;
  border-radius: 30rpx;
  line-height: 1.5;
}
.no-schedule {
  text-align: center;
  color: #999;
  padding: 100rpx 0;
}
</style>